package cn.edu.sdjzu.xg.bysj.filter;

import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "EncodingFilter",urlPatterns = {"/*"})
@Slf4j
public class EncodingFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.trace("字符编码过滤器启用");
        //强制类型转换
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;
        //获得请求方法类型，储存为String字段
        String method = httpServletRequest.getMethod();
        String url =httpServletRequest.getRequestURI();
        log.trace(method + "方法");
        //如果是删除方法只需设置响应格式
        if (method.contains("DELETE")){
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            log.trace("删除方法只设置响应格式");
        }else {//如果是其他三种方法则设置响应与请求格式
            httpServletRequest.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            log.trace("设置请求与响应格式");
        }
        //执行过滤器链
        chain.doFilter(request,response);
        log.trace("字符编码过滤器结束");
    }
}
